<?php

namespace App\Helpers;

use CodeIgniter\HTTP\Files\UploadedFile;
use CodeIgniter\HTTP\URI;

class CommonUtil
{
    /**
     * @param UploadedFile $file
     * @param string|NULL $prefix
     * @param string|NULL $filename
     * @return string
     * @throws \Exception
     */
    public static function getUploadFilePath(UploadedFile $file, string $prefix = NULL, string $filename = NULL): string
    {
        if (!$file->isValid()) throw new \Exception($file->getErrorString());

        $uri  = new URI(site_url());
        $name = $filename ?? $file->getRandomName();

        return "{$uri->getScheme()}://{$uri->getHost()}/uploads/{$file->store($prefix, $name)}";
    }

    public static function deletePath($path)
    {
        helper('filesystem');

        $d = directory_map($path, 1, true);
        foreach ($d as $f) {
            if (is_dir($path .'/'. $f)) {
                self::deleteDir($path .'/'. $f);
            } else {
                @unlink($f);
            }
        }
    }

    public static function deleteDir($path)
    {
        if (is_dir($path)) {
            $dirs = scandir($path);

            foreach ($dirs as $dir) {
                if ($dir != '.' && $dir != '..') {
                    $sonDir = $path . '/' . $dir;

                    if (is_dir($sonDir)) {
                        self::deleteDir($sonDir);
                    } else {
                        @unlink($sonDir);
                    }
                }
            }

            @rmdir($path);
        }
    }
}